<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>数据大盘</h1>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日取号总数</span>
              <el-tooltip content="今日发出的所有排队号码数量" placement="top">
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">{{ todayStats.totalTickets }}</div>
            <div class="card-trend" :class="{'up': todayStats.ticketsTrend > 0, 'down': todayStats.ticketsTrend < 0}">
              {{ todayStats.ticketsTrend > 0 ? '+' : '' }}{{ todayStats.ticketsTrend }}%
              <el-icon v-if="todayStats.ticketsTrend > 0"><ArrowUp /></el-icon>
              <el-icon v-else-if="todayStats.ticketsTrend < 0"><ArrowDown /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日办理业务</span>
              <el-tooltip content="今日成功办理的业务数量" placement="top">
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">{{ todayStats.completedServices }}</div>
            <div class="card-trend" :class="{'up': todayStats.servicesTrend > 0, 'down': todayStats.servicesTrend < 0}">
              {{ todayStats.servicesTrend > 0 ? '+' : '' }}{{ todayStats.servicesTrend }}%
              <el-icon v-if="todayStats.servicesTrend > 0"><ArrowUp /></el-icon>
              <el-icon v-else-if="todayStats.servicesTrend < 0"><ArrowDown /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均等待时间</span>
              <el-tooltip content="客户从取号到叫号的平均等待时间" placement="top">
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">{{ formatTime(todayStats.avgWaitTime) }}</div>
            <div class="card-trend" :class="{'up': todayStats.waitTimeTrend > 0, 'down': todayStats.waitTimeTrend < 0}">
              {{ todayStats.waitTimeTrend > 0 ? '+' : '' }}{{ todayStats.waitTimeTrend }}%
              <el-icon v-if="todayStats.waitTimeTrend > 0"><ArrowUp /></el-icon>
              <el-icon v-else-if="todayStats.waitTimeTrend < 0"><ArrowDown /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均服务时间</span>
              <el-tooltip content="客户从开始办理到完成的平均时间" placement="top">
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">{{ formatTime(todayStats.avgServiceTime) }}</div>
            <div class="card-trend" :class="{'up': todayStats.serviceTimeTrend > 0, 'down': todayStats.serviceTimeTrend < 0}">
              {{ todayStats.serviceTimeTrend > 0 ? '+' : '' }}{{ todayStats.serviceTimeTrend }}%
              <el-icon v-if="todayStats.serviceTimeTrend > 0"><ArrowUp /></el-icon>
              <el-icon v-else-if="todayStats.serviceTimeTrend < 0"><ArrowDown /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>近7天业务量趋势</span>
            </div>
          </template>
          <div class="chart-container" ref="weeklyChartRef"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>业务类型分布</span>
            </div>
          </template>
          <div class="chart-container" ref="businessTypeChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时队列状态 -->
    <el-card class="queue-status-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>实时队列状态</span>
          <el-button type="primary" size="small" @click="refreshQueueStatus">刷新</el-button>
        </div>
      </template>
      <el-table :data="queueStatusList" style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="businessType" label="业务类型" />
        <el-table-column prop="totalTickets" label="总人数" />
        <el-table-column prop="noShowCount" label="未到达人数" />
        <el-table-column prop="waitingCount" label="等待人数" />
        <el-table-column prop="completedCount" label="今日已完成" />
        <el-table-column prop="avgWaitTime" label="平均等待时间">
          <template #default="scope">
            {{ formatTime(scope.row.avgWaitTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart, PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { InfoFilled, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import axios from "axios";
import {getLastDay, getLastWeekDay, getToday} from "@/utils/date";

// 注册必要的echarts组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  PieChart,
  CanvasRenderer
])

let businessTypeMap = new Map();
function initData() {
  axios.get("/service-types/getList", {
    params: {
      "pageNum": 1,
      "pageSize": 100,
      "status": 1,
    }
  }).then(res => {
    res.data.data.list.forEach(item => {
      businessTypeMap.set(item.id, item);
    })
  });
  setTimeout(() => {
    getQueueStatusList();
    loadWeeklyChart()
    loadBusinessTypeChart()
  }, 200);
}

// 今日统计数据
const todayStats = reactive({
  totalTickets: 0,
  ticketsTrend: 12,
  completedServices: 0,
  servicesTrend: 8,
  avgWaitTime: 0,  // 15分钟
  waitTimeTrend: -5, // 下降5%
  avgServiceTime: 0, // 12分钟
  serviceTimeTrend: 3 // 上升3%
})
axios.get('/statistics/daily', {
  params: {
    date: getToday(),
    serviceTypeId: null
  }
}).then((res) => {
  res.data.data.forEach((item) => {
    todayStats.totalTickets += item.totalTickets;
    todayStats.completedServices += item.completedCount;
    todayStats.avgWaitTime += item.avgWaitTime;
    todayStats.avgServiceTime += item.avgServiceTime;
  })
  // 获取昨日数据
  axios.get('/statistics/daily', {
    params: {
      date: getLastDay(),
      serviceTypeId: null
    }
  }).then((res) => {
    let lastTickets = 0;
    let lastServices = 0;
    let lastAvgWaitTime = 0;
    let lastAvgServiceTime = 0;
    res.data.data.forEach((item) => {
      lastTickets += item.totalTickets;
      lastServices += item.completedCount;
      lastAvgWaitTime += item.avgWaitTime;
      lastAvgServiceTime += item.avgServiceTime;
    });
    todayStats.ticketsTrend = Math.floor((todayStats.totalTickets - lastTickets) / lastTickets * 100);
    todayStats.servicesTrend = Math.floor((todayStats.completedServices - lastServices) / lastServices * 100);
    todayStats.waitTimeTrend = Math.floor((todayStats.avgWaitTime - lastAvgWaitTime)
        / lastAvgWaitTime * 100);
    todayStats.serviceTimeTrend = Math.floor((todayStats.avgServiceTime - lastAvgServiceTime)
        / lastAvgServiceTime * 100);
  });
});




// 近7天业务量数据
const weeklyData = reactive({
  dates: [],
  tickets: [],
  completed: []
})
axios.post('/statistics/range', {
  "startDate":getLastWeekDay(),"endDate":getToday(),"type":"daily"
}).then(res => {
  if (res.data.data && res.data.data.length > 0) {
    let tempDay = res.data.data[0].statDate;
    let index = 0;
    weeklyData.dates[0] = res.data.data[0].statDate;
    weeklyData.tickets[0] = res.data.data[0].totalTickets;
    weeklyData.completed[0] = res.data.data[0].completedCount;
    res.data.data.forEach((item) => {
      if (item.statDate !== tempDay) {
        index++;
        tempDay = item.statDate;
        weeklyData.dates[index] = item.statDate;
        weeklyData.tickets[index] = item.totalTickets;
        weeklyData.completed[index] = item.completedCount;
      } else {
        weeklyData.tickets[index] += item.totalTickets;
        weeklyData.completed[index] += item.completedCount;
      }
    })
  }
});


// 业务类型分布
let businessTypeData = reactive([
  {
    "value": 60,
    "name": "个人业务"
  },
  {
    "value": 20,
    "name": "企业业务"
  },
  {
    "value": 20,
    "name": "信贷业务"
  },
  {
    "value": 0,
    "name": "理财业务"
  },
  {
    "value": 0,
    "name": "外汇业务"
  },
  {
    "value": 0,
    "name": "咨询业务"
  }
])


// 排队状态列表
const queueStatusList = ref([

])

// 表格加载状态
const tableLoading = ref(false)

// 图表引用
const weeklyChartRef = ref(null)
const businessTypeChartRef = ref(null)
let weeklyChart = null
let businessTypeChart = null

// 日期范围
const dateRange = ref([
  new Date(new Date().setDate(new Date().getDate() - 6)), // 7天前
  new Date() // 今天
])

// 格式化时间
const formatTime = (minutes) => {
  if (!minutes) return '0分钟'

  if (minutes < 60) {
    return `${minutes}分钟`
  } else {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'ACTIVE': 'success',
    'INACTIVE': 'info',
    'BUSY': 'warning',
    'CLOSED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'ACTIVE': '活跃',
    'INACTIVE': '不活跃',
    'BUSY': '繁忙',
    'CLOSED': '关闭'
  }
  return statusMap[status] || '未知'
}

// 加载周数据图表
const loadWeeklyChart = () => {
  if (!weeklyChartRef.value) return

  if (weeklyChart) {
    weeklyChart.dispose()
  }

  weeklyChart = echarts.init(weeklyChartRef.value)

  const option = {
    title: {
      text: '近7天业务量趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['取号量', '办理量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: weeklyData.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '取号量',
        type: 'line',
        data: weeklyData.tickets,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#5470c6'
        },
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '办理量',
        type: 'line',
        data: weeklyData.completed,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#91cc75'
        },
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  }
  console.log("weeklyChart---" +option)
  weeklyChart.setOption(option)
  console.log("weeklyChart---end")
}

// 加载业务类型分布图表
const loadBusinessTypeChart = () => {
  if (!businessTypeChartRef.value) return

  if (businessTypeChart) {
    businessTypeChart.dispose()
  }

  businessTypeChart = echarts.init(businessTypeChartRef.value)
  const option = {
    title: {
      text: '业务类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: businessTypeData.map(item => item.name)
    },
    series: [
      {
        name: '业务类型',
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        data: businessTypeData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}: {d}%'
        }
      }
    ]
  }
  console.log("businessTypeChart---" +option)
  businessTypeChart.setOption(option)
  console.log("businessTypeChart---end")
}

// 加载周数据
const loadWeeklyData = () => {
  if (!dateRange.value || dateRange.value.length !== 2) return

  // 这里使用模拟数据
  // 在实际场景中，这里会调用API根据日期范围获取数据
  console.log('加载从', dateRange.value[0], '到', dateRange.value[1], '的数据')

  // 仅模拟刷新图表
  loadWeeklyChart()
}

// 刷新队列状态
const refreshQueueStatus = () => {
  getQueueStatusList();
}

function getQueueStatusList() {
  tableLoading.value = true
  axios.get("/statistics/by-business-type", {
    params: {
      startDate: getToday(),
      endDate: getToday()
    }
  }).then(res => {
    queueStatusList.value = [];
    let totoCompletedCount = 0;
    res.data.data.forEach(item => {
      totoCompletedCount += item.completedCount;
    })
    res.data.data.forEach(item => {
      item.businessType = businessTypeMap.get(parseInt(item.serviceTypeId)).name;
      queueStatusList.value.push(item);
      let data = {
        value: Math.floor((item.completedCount/totoCompletedCount) * 100),
        name: item.businessType
      }
      businessTypeData.push(data)
    })
    console.log(businessTypeData)
    tableLoading.value = false
  });
}

// 窗口大小改变时重置图表大小
const handleResize = () => {
  if (weeklyChart) {
    weeklyChart.resize()
  }
  if (businessTypeChart) {
    businessTypeChart.resize()
  }
}

onMounted(() => {
  console.log('进入数据大盘')
  // 加载图表
  initData();
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  if (weeklyChart) {
    weeklyChart.dispose()
  }
  if (businessTypeChart) {
    businessTypeChart.dispose()
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 15px 0;
}

.dashboard-header {
  margin-bottom: 20px;
}

.dashboard-header h1 {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: 100%;
  border-radius: 8px;
  transition: transform 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
}

.card-body {
  text-align: center;
  padding: 10px 0;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.card-trend {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.card-trend.up {
  color: #67C23A;
}

.card-trend.down {
  color: #F56C6C;
}

.info-icon {
  margin-left: 5px;
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.queue-status-card {
  border-radius: 8px;
}
</style>
